package com.itheima.service.impl;

import com.itheima.common.AuthThreadLocal;
import com.itheima.common.CustomException;
import com.itheima.utils.SnowflakeUtils;
import com.itheima.entity.Employee;
import com.itheima.mapper.EmployeeMapper;
import com.itheima.service.EmployeeService;
import com.itheima.vo.EmployeeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

;

/**
 * @Author HeiMa-sw
 * @Description 员工业务层实现类//TODO 17210
 * @Date 15:52 2022/6/7
 **/
@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private SnowflakeUtils snowflakeUtils;

    @Override
    public EmployeeVo getPage(Integer page, Integer pageSize, String name) {
        EmployeeVo employeeVo = new EmployeeVo();
        employeeVo.setCurrent(page);
        if (page == 1) {
            page = 0;
        } else {
            page = (page - 1) * pageSize;
        }
        List<Employee> empList = employeeMapper.page(page, pageSize, name);
        employeeVo.setRecords(empList);
        employeeVo.setTotal(employeeMapper.selectCount());
        employeeVo.setSize(pageSize);
        return employeeVo;
    }

    @Override
    @Transactional
    public Employee saveOne(Employee employee) {
        employee.setId(String.valueOf(snowflakeUtils.snowflakeId()));
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        employee.setStatus(1);
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        String empId = AuthThreadLocal.getAuth();
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);
        employeeMapper.insertOne(employee);
        return employee;
    }

    @Override
    @Transactional
    public Employee modifyOne(final Employee employee) {
        employee.setUpdateUser(AuthThreadLocal.getAuth());
        employee.setUpdateTime(LocalDateTime.now());
        Employee one = employeeMapper.selectByUsername(employee.getUsername());
        if (one == null){
            employeeMapper.updateOne(employee);
            return employee;
        }else {
            throw new CustomException("用户名已存在");
        }

    }

    @Override
    public Employee getOne(final String username, final String password) {
        return employeeMapper.selectOne(username, password);
    }

    @Override
    public Employee getByIdOrName(final String condition) {
        return employeeMapper.selectByIdOrName(condition);
    }


}
